/**
 * @include "libs/jquery-1.3.2.js" 
 * @include "utils.js"
 * @include "config.js"
 */

/**
 * MAIN MODULE
 * 
 * All tools the map, it's here
 * Todas las herramientas del mapa estan aqui.
 * 
 * para mas info: http://code.google.com/apis/maps/documentation/reference.html
 */

//unique global var.
var map = null;

m = {
	/* CONSTANTS */
	VARS_LANG : "0", //language
	VARS_LL : "1", //lattitude and longitude
	VARS_ZOOM : "2", //zoom
	VARS_TYPEMAP : "3", //typemap
	
	TYPE_NORMAL_MAP : "m", //vectorial map
	TYPE_SATELLITE_MAP : "k", //satelital map
	TYPE_HYBRID_MAP : "h", //saltelital and vectorial map
	TYPE_PHYSICAL_MAP : "p", //phisical map (green)
	TYPE_SATELLITE_3D_MAP : "e", //with google earth plugin for browser
	
	/* VARIABLES: */
	arrQS:[], //Array with data parsed of querystring
	user_lang:null, //language of user
	user_ll:null, //latitude & longitude saved
	user_zoom:null, //zoom saved
	user_typeMap:"", //tymeMap saved
	share_url:"", //url "share it"
	geoXml:[], //kml loaded into this array
	countKml:0,
	
	/**
	 * Inicialization of this module
	 */
	ini:function(){
		config.ini();
		text.loadText();
		
		m.loadPreferences();
		m.loadGoogleMapScript();
	},
	
	/**
	 * Script Google AJAX API for Load map dinamicaly, with key. 
	 * Este script es de google AJAX API para cargar modulos dinamicamente, incluye el key de google maps  
	 * 
	 * @see http://code.google.com/apis/maps/signup.html
	 * @see http://code.google.com/apis/ajax/documentation/#GoogleLoad
	 */
	loadGoogleMapScript:function() {
		//After to load map, call to loadGoogleMaps() -- Luego de cargar el mapa invoca por callback a loadGoogleMaps
		utils.loadJavascript('http://www.google.com/jsapi?key='+ config.key +'&callback=m.loadGoogleMaps');
		//'http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key='+ config.key +'&hl='+ m.user_lang +'&async=2&callback=m.loadMap');
	},
	
	loadGoogleMaps:function(){
		google.load("maps", "2.x", {"callback" : m.loadMap,
									"other_params":"sensor=false",
									"async":2,
									"language":m.user_lang});
	},
	
	/**
	 * Load and renderer the map
	 * carga y muestra el mapa
	 * */
	loadMap : function() {
		var gsBrowserIsCompatible;
		try {
			gsBrowserIsCompatible = GBrowserIsCompatible();
		} catch (e) {
			//Not load google maps error
			alert(m.text.g(m.text.ER_NO_LOAD_MAP));
			return;
		}
		
		if (gsBrowserIsCompatible){
			var ll = m.user_ll.split(",");

			//opciones a cambiar
			var mapOptions = {
    			googleBarOptions : {
      			style : "new"
    		}};
    		//end opciones
    		
			map = new GMap2(document.getElementById('div_map'),mapOptions);
			map.setCenter(new GLatLng(ll[0], ll[1]), parseInt(m.user_zoom));
			
			// change customs properties  (http://code.google.com/intl/en/apis/maps/documentation/reference.html#GControl)
			map.setMapType(m.getMapType(m.user_typeMap));
			map.addControl(new GMenuMapTypeControl());
			map.addControl(new GOverviewMapControl());
			map.addControl(new GLargeMapControl3D());
			
			map.addMapType(m.getMapType(m.TYPE_PHYSICAL_MAP));
			map.addMapType(m.getMapType(m.TYPE_SATELLITE_3D_MAP));
			map.enableGoogleBar();
			map.enableScrollWheelZoom();
			map.enableContinuousZoom();
			
			//others posibles:
			//map.addControl(new GLargeMapControl());
			//map.setUIToDefault();
			
			//end custom properties
			m.updateMap();
			
			//EVENTS
			GEvent.addListener(map, 'zoomend', function() {
				m.updateMap();
			});
			GEvent.addListener(map, 'moveend', function() {
				m.updateMap();
			});
			GEvent.addListener(map, 'maptypechanged', function() {
				m.updateMap();
			});
			
			m.insertLogos();
			
			m.loadKmls();
		}
		if(m.countKml<=0){
			m.hideLoadingBar();
			m.hideBlock();
		}
	},
	
	/**
	 * this method update all varibles and make url to share
	 */
	updateMap:function(){
		m.user_ll = map.getCenter().lat() + ","+ map.getCenter().lng();
		m.user_zoom = parseInt(map.getZoom());
		m.user_typeMap = map.getCurrentMapType().getUrlArg();
		
		m.updateShares();
	},
	
	updateShares:function(){
		m.share_url =
			'll=' + m.user_ll +
			'&z='+ m.user_zoom +
			'&tm='+ m.user_typeMap;
					
		
		$('#share_mail').attr("href", "mailto:?subject=Easy Google Maps&body=Hi!, look this: "+ utils.urlencode(location.href + m.share_url)+", this is Easy Google Maps");
		$('#popup_share_textbox').attr("value", location.href +"?"+ utils.urlencode(m.share_url));
		$('#share_del').attr("href", "http://del.icio.us/post?url="+ utils.urlencode(location.href + m.share_url) + "&title="+ config.share_title);
		$('#share_fb').attr("href", "http://www.facebook.com/share.php?u="+ utils.urlencode(location.href + m.share_url) + "&t="+ config.share_title);
		$('#share_google').attr("href", "http://www.google.com/bookmarks/mark?op=add&bkmk="+ utils.urlencode(location.href + m.share_url) + "&title="+ config.share_title);
		$('#share_live').attr("href", "https://favorites.live.com/quickadd.aspx?url="+ utils.urlencode(location.href + m.share_url));
		$('#share_myspac').attr("href", "http://www.myspace.com/index.cfm?fuseaction=postto&u="+ utils.urlencode(location.href + m.share_url) + "&t="+ config.share_title);
	},
	
	/**
	 * Load kmls loaded in config.kmls
	 */
	loadKmls:function(){
		m.geoXml = new Array();
		m.showLoadingBar();
		for(var i in config.kmls) {
			m.countKml++;
			m.loadKml(config.kmls[i]);
		}
	},
	
	/**
	 * load individual kml
	 * @param {} config.kmls[]
	 * @return {} id to kml
	 */
	loadKml:function(kml){
		var geoXml = new GGeoXml(kml.url)
		
		GEvent.addListener(geoXml, 'load', function() {
			if (geoXml.loadedCorrectly()) {
				if(kml.center){
					geoXml.gotoDefaultViewport(map);
				}
				m.countKml--;
				if(m.countKml<=0){
					m.hideBlock();
					m.hideLoadingBar();
				}
			}else{
				alert(text.g(text.ER_NO_LOAD_KML));
			}
		});
		
		m.geoXml[kml.id] = geoXml;
		map.addOverlay(m.geoXml[kml.id]);
		m.showLoadingBar();
		return kml.id;
	},
	
	/**
	 * insert logo and image background in the map
	 */
	insertLogos:function(){
		$('#div_map').css('background-image', 'url('+config.backgroundImage+')');
		
		var logo = new GScreenOverlay(config.logo,
			new GScreenPoint(5, 35, 'pixels', 'pixels'),  // screenXY
			new GScreenPoint(0, 0),  // overlayXY
			new GScreenSize(233, 42)  // size on screen
		);
		map.addOverlay(logo);
	},
	
	changeSize:function(){
		if (!$("#map")){return;}
		var height = (utils.getWindowHeight() - ($('#div_foot').get(0).offsetHeight));
		var width = utils.getWindowWidth();
		
		$('#canvas_center').css('top', height/2 + 'px');
		$('#canvas_center').css('left', width/2 + 'px');
		
		$('#div_map').css('height', height + 'px');
		$('#div_map').css('width', width + 'px');
		
		$('#canvas_block').css('height', height + 'px');
		$('#canvas_block').css('width', width + 'px');
		
		$('#canvas').css('height', utils.getWindowHeight() + 'px');
		$('#canvas').css('width', width + 'px');
	},

	toggleShare:function(){
		if($("#popup_share").css("display") == "none"){
			m.showShare();
			$("#popup_share_textbox").focus( function(){
				this.select();
			});
			$("#popup_share_textbox").focus();	
		}else{
			m.hideShare();		
		}
	},
	
	showShare:function(){
		$("#popup_share").show();
		$("#popup_share").animate({"opacity":0.9});
		m.showBlock();	
	},
	
	hideShare:function(){
		$("#popup_share").hide();
		m.hideBlock();	
	},
	
	showBlock:function(){
		$('#canvas_block').animate({"opacity":0.5});
	},
	
	hideBlock:function(){
		$('#canvas_block').animate({"opacity":0.0},"low");
		setTimeout(function(){$('#canvas_block').hide()},1000);
	},
	
	showLoadingBar:function(){
		$('#div_loading').show();	
	},
	
	hideLoadingBar:function(){
		$('#div_loading').hide();	
	},
	
	/**
	 * get type map with your charater
	 * @param {} char
	 * @return {} object
	 */
	getMapType:function(arg){
		switch (arg){
			case "m": return G_NORMAL_MAP;break;
			case "k": return G_SATELLITE_MAP;break;
			case "h": return G_HYBRID_MAP;break;
			case "p": return G_PHYSICAL_MAP;break;
			case "e": return G_SATELLITE_3D_MAP;break;
		}
	},
	
	/**
	 * load preferences, location, language and others
	 */
	loadPreferences : function() {
		//First the cookies
		if (config.useCookie && document.cookie.length > 0) {
			var cookieStart = document.cookie.indexOf(config.cookiename + "=");
			if (cookieStart != -1) {
				cookieStart += config.cookiename.length + 1;
				var cookieEnd = document.cookie.indexOf(";", cookieStart);
				if (cookieEnd == -1) {
					cookieEnd = document.cookie.length;
				}
				var cookietext = document.cookie.substring(cookieStart, cookieEnd);
				var data = cookietext.split("|");
				//l(data);
				m.user_lang = data[m.VARS_LANG];
				m.user_ll =  data[m.VARS_LL];
				m.user_zoom = parseInt(data[m.VARS_ZOOM]);
				m.user_typeMap = data[m.VARS_TYPEMAP];
			}
		}
		
		//Second, queryString
		m.arrQS = utils.QS2Array();

		if(m.arrQS["lang"]!=null){
			m.user_lang=m.arrQS["lang"];
		}
		if(m.arrQS["z"]!=null){
			m.user_zoom=m.arrQS["z"];
		}
		if(m.arrQS["tm"]){
			m.user_typeMap = m.arrQS["tm"];
		}
		
		if(m.arrQS["ll"]){
			m.user_ll = m.arrQS["ll"];
		}
		
		// VALIDATIONS, and load values for defaults
		if(m.user_lang == null || (m.user_lang != config.LANG_EN && m.user_lang != config.LANG_ES)){
			m.user_lang = utils.detectLang();
			//l("detect your language " +m.user_lang);
			
			if((m.user_lang != config.LANG_EN && m.user_lang != config.LANG_ES)){
				//l("load lang default");
				m.user_lang = config.LANG_DEFAULT;
			}
		}
		
		if(m.user_zoom == null || (isNaN(parseInt(m.user_zoom)))){
			//l("load zoom default");
			m.user_zoom = config.zoom;
		}
		
		if(m.user_typeMap == null || 
			(m.user_typeMap != m.TYPE_NORMAL_MAP &&
			m.user_typeMap != m.TYPE_SATELLITE_MAP &&
			m.user_typeMap != m.TYPE_HYBRID_MAP &&
			m.user_typeMap != m.TYPE_PHYSICAL_MAP &&
			m.user_typeMap != m.TYPE_SATELLITE_3D_MAP)){
				//l("carga typemap default");
				m.user_typeMap = config.typeMap;
		}
		
		//validation latitude and longitude
		if(m.user_ll == null){
			//l("load for defect")
			m.user_ll = config.lat + ","+ config.lng;
		}else{
			var ll = m.user_ll.split(",");
			if(ll.length!=2){
				//l("distint of two");
				m.user_ll = config.lat + ","+ config.lng;
			}else if(!isNaN(parseFloat(ll[0])) && !isNaN(parseFloat(ll[1]))){
				//l("parece validad");
				m.user_ll = parseFloat(ll[0]) + ","+ parseFloat(ll[1]);
			}else{
				//l("no valida");
				m.user_ll = config.lat + ","+ config.lng;
			}
		}
	},
	
	exitMap:function(){
		if(config.useCookie){
			m.saveCookieMap();
		}
		GUnload();
	},
	
	saveCookieMap : function() {
		var data = new Array();
		data[m.VARS_LANG] = m.user_lang;
		data[m.VARS_LL] = m.user_ll;
		data[m.VARS_ZOOM] = m.user_zoom;
		data[m.VARS_TYPEMAP] = m.user_typeMap;
		
		var cookietext = config.cookiename + "=";
		
		for (var i = 0; i < data.length; i++) {
			cookietext += data[i]+"|";
		}

		var exdate = new Date();
		exdate.setDate(exdate.getDate() + config.expiredays);
		cookietext += ";expires=" + exdate.toGMTString();

		document.cookie = cookietext;
	},
	
	l : function(str) {
		GLog.write(str);
	}

};

